package com.my.bytes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author: marshal
 * @date: 2021-09-27 8:52 PM
 *
 * 字节流测试
 */
public class ByteIODemo {
    public static void main(String[] args) {
        String writePath = "file/byte_io_write.txt";
        // 1. 写入数据
        testWrite(writePath, "给时光以生命，给岁月以文明。");
        // 2. 读取数据
        testRead(writePath);

    }


    /**
     *  读取数据
     *
     * @param path
     */
    private static void testRead(String path) {
        try (var in = new FileInputStream(path)) {
            // 每次输出一个字节
//            while (in.read() != -1) {
//                System.out.println(in.read());
//            }
            // 每个汉字字符都是占用3个字节，所以用长度为3字节的byte数组来读取数据
            byte[] bbuf = new byte[3];
            int lenth = 0;
            while ((lenth = in.read(bbuf)) > 0) {
                System.out.println(new String(bbuf, 0, lenth));
            }
        } catch (IOException e) {
            System.out.println("read error => " + e.getMessage());
        }
    }

    /**
     *  通过字节流保存数据
     *
     * @param path
     * @param data
     */
    private static void testWrite(String path, String data) {
        try (var out = new FileOutputStream(path)) {
            byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
            out.write(bytes);
            System.out.println("write success.");
        } catch (IOException e) {
            System.out.println("write error => " + e.getMessage());
        }
    }
}
